package com.shkco.user.service.impl;

import com.shkco.basic.exception.BusinessException;
import com.shkco.basic.util.Md5Utils;
import com.shkco.basic.util.StrUtils;
import com.shkco.org.domain.Employee;
import com.shkco.org.domain.Shop;
import com.shkco.user.domain.Logininfo;
import com.shkco.user.domain.User;
import com.shkco.user.dto.EmailDto;
import com.shkco.user.dto.UserDto;
import com.shkco.user.mapper.LogininfoMapper;
import com.shkco.user.mapper.UserMapper;
import com.shkco.user.service.IUserService;
import com.shkco.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String pwdRepeat = userDto.getPwdRepeat();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(pwdRepeat)){
            throw new BusinessException("信息不能为空!");
        }
        if (!pwd.equals(pwdRepeat)){
            throw new BusinessException("两次密码不一致!请重新输入!");
        }

        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        if (codeObj == null){
            throw new BusinessException("手机验证码过期！");
        }
        if (!codeObj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("手机验证码错误！");
        }

        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    @Override
    public void emailRegister(EmailDto emailDto) throws MessagingException {
        String email = emailDto.getEmail();
        String pwd = emailDto.getPwd();
        String pwdRepeat = emailDto.getPwdRepeat();
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(pwdRepeat)){
            throw new BusinessException("信息不能为空!");
        }
        if (!pwd.equals(pwdRepeat)){
            throw new BusinessException("两次密码不一致!请重新输入!");
        }
        User user = emailDto2User(emailDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
        // 发送邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        helper.setFrom("1582002603@qq.com");
        helper.setSubject("用户注册邮件");
        helper.setText("<h1>注册成功!!!</h1><h3><a href='http://127.0.0.1:8080/user/active/"+user.getId()+"'>点击该链接激活账户</a></h3>",true);
        helper.setTo(user.getEmail());
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void active(Long id) {
        User user = userMapper.findById(id);
        user.setState(1);
        userMapper.update(user);
    }

    private User emailDto2User(EmailDto emailDto) {
        User user = new User();
        user.setEmail(emailDto.getEmail());
        user.setUsername(emailDto.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(emailDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(0);
        return user;
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    @Transactional
    public void add(User user) {
        // 使用工具类生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 使用工具类加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        // 给user设置盐值
        user.setSalt(salt);
        // 设置密码
        user.setPassword(md5Pwd);
        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        // 使用工具类拷贝
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);
        // 保存user
        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }

    @Override
    @Transactional
    public void update(User user) {
        // 使用工具类生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 使用工具类加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        // 给user设置盐值
        user.setSalt(salt);
        // 设置密码
        user.setPassword(md5Pwd);
        super.update(user);
        // 获取登录信息id
        Long logininfoId = userMapper.findById(user.getId()).getLogininfoId();
        // 获取logininfo对象
        Logininfo logininfo = logininfoMapper.findById(logininfoId);
        // 将原有的数据覆盖
        BeanUtils.copyProperties(user,logininfo);
        logininfoMapper.update(logininfo);
    }

    @Override
    @Transactional
    public void del(Long id) {
        User user = userMapper.findById(id);
        logininfoMapper.del(user.getLogininfoId());
        super.del(id);
    }
}
